package com.newenergy.wisehome.gateway.family;


import android.app.AlertDialog;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.gateway.adapter.BLFamilyAdapter;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.broadlink.base.BLBaseResult;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.family.params.BLFamilyBaseInfo;
import cn.com.broadlink.family.params.BLFamilyInfo;
import cn.com.broadlink.family.result.BLFamilyBaseInfoListResult;

/**
 * A simple {@link Fragment} subclass.
 */
public class BLFamilyListFragment extends BaseFragment {

    Unbinder unbinder;
    private ArrayList<BLFamilyInfo> mData;
    private BLFamilyAdapter mAdapter;
    @BindView(R.id.tv_page)
    TextView mTvPage;

    @BindView(R.id.rv_bl_family)
    EasyRecyclerView mRecyclerView;
    private BLFamilyInfo mFamilyInfo;

    private Handler mHandler = new Handler();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_blfamily_list;
    }


    @Override
    public void init(View rootView) {
        mTvPage.setText("BL家庭列表");
        mData = new ArrayList<>();
        mAdapter = new BLFamilyAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        mAdapter.setOnItemClickListener(position -> {
            BLFamilyInfo familyInfo = mAdapter.getItem(position);
            toast(familyInfo.getFamilyName());
        });
        mAdapter.setOnItemLongClickListener(position -> {
            mFamilyInfo = mAdapter.getItem(position);
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("提示")
                    .setMessage("是否要删除 " + mFamilyInfo.getFamilyName() + "?")
                    .setNegativeButton("取消", (dialog, which) -> {
                        dialog.dismiss();
                    })
                    .setPositiveButton("确定", (dialog, which) -> {
                        dialog.dismiss();
                        delBLFamilyTask();
                    });
            builder.show();
            return true;
        });
        queryAllBLFamily();
    }

    private void queryAllBLFamily() {
        MyThreadManager.getInstance().doTask(() -> {
            BLFamilyBaseInfoListResult result = BLFamily.queryLoginUserFamilyBaseInfoList();
            mHandler.post(() -> updateQueryAllBLFamily(result));
        });
    }

    private void updateQueryAllBLFamily(BLFamilyBaseInfoListResult result) {
        if (result != null && result.succeed()) {
            toast("查询成功");
            List<BLFamilyBaseInfo> baseInfos = result.getInfoList();
            if (baseInfos != null && baseInfos.size() > 0) {
                List<BLFamilyInfo> familyInfos = new ArrayList<>();
                for (BLFamilyBaseInfo baseInfo : baseInfos) {
                    BLFamilyInfo familyInfo = baseInfo.getFamilyInfo();
                    familyInfos.add(familyInfo);
                }
                mAdapter.addAll(familyInfos);
            }
        } else {
            toast("查询失败");
            if (result != null) {
                String tag = "updateQueryAllBLFamily";
                showBLLog(result, tag);
            }
        }
    }

    private void showBLLog(BLBaseResult result, String tag) {
        Log.i(TAG, tag + ": success = " + result.succeed() + " error =  " + result.getError() + "  msg=" + result.getMsg());
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @OnClick({R.id.btn_back, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
        }
    }


    public void delBLFamilyTask() {
        MyThreadManager.getInstance().doTask(() -> {
            BLBaseResult result = BLFamily.delFamily(mFamilyInfo.getFamilyId(), mFamilyInfo.getFamilyVersion());
            mHandler.post(() -> updateDelBLFamily(result));
        });
    }

    private void updateDelBLFamily(BLBaseResult result) {
        if (result != null && result.succeed()) {
            toast("删除家庭成功");
            mAdapter.remove(mFamilyInfo);
        } else {
            toast("删除家庭失败");
            showBLLog(result, "删除家庭失败");
        }

    }


//    private class QueryAllBLFamilyTask extends AsyncTask<Void, Void, Void> {
//        @Override
//        protected Void doInBackground(Void... voids) {
//            mData.clear();
//            BLFamilyBaseInfoListResult result = BLFamily.queryLoginUserFamilyBaseInfoList();
//            if (result != null && result.succeed()) {
//                List<BLFamilyBaseInfo> baseInfos = result.getInfoList();
//                if (baseInfos != null && baseInfos.size() > 0) {
//                    for (BLFamilyBaseInfo baseInfo : baseInfos) {
//                        BLFamilyInfo familyInfo = baseInfo.getFamilyInfo();
//                        String familyName = familyInfo.getFamilyName();
//                        String familyId = familyInfo.getFamilyId();
//                        Log.i(TAG, "familyInfo: familyName = " + familyName + "  familyId = " + familyId);
//                        mData.add(familyInfo);
//                    }
//                }
//            }
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Void result) {
//            super.onPostExecute(result);
//            mAdapter.notifyDataSetChanged();
//
//        }
//    }
//
//    private class DelBLFamilyTask extends AsyncTask<Void, Void, Void> {
//        @Override
//        protected Void doInBackground(Void... voids) {
//            BLBaseResult result = BLFamily.delFamily(mFamilyInfo.getFamilyId(), mFamilyInfo.getFamilyVersion());
//            if (result != null && result.succeed()) {
//                mData.remove(mFamilyInfo);
//            }
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Void result) {
//            super.onPostExecute(result);
//            mAdapter.notifyDataSetChanged();
//
//        }
//    }
}
